Bubble Sort - O(N^2) - Sorting by Exchange¶
Bubble sort, sometimes referred to as sinking sort, is a simple sorting
algorithm that repeatedly steps through the list to be sorted, compares
each pair of adjacent items and swaps them if they are in the wrong order.
The pass through the list is repeated until no swaps are needed, which
indicates that the list is sorted.
The algorithm, which is a comparison sort, is named for the way smaller
elements “bubble” to the top of the list.
Although the algorithm is simple, it is TOO SLOW and impractical for most
problems even when compared to insertion sort. It can be practical
if the input is usually in sort order but may occasionally have some
out-of-order elements nearly in position.”
Sample Data:
[4, 10, 8, 12, 6, 14, 2, 16, 1]
Expected Result:
[1, 2, 4, 6, 8, 10, 12, 14, 16]
def bubbleSort(L):
for i in range(len(L)-1, 0 ,-1):
print('i=', i, '|', '\t\t\t\t', L)
for j in range(i):
if L[j] > L[j + 1]:
# Swap values
print('i=', i, '|', L[j], '<->', L[j+1],'=>\t', end ='')
L[j], L[j + 1] = L[j + 1], L[j]
print(L)
print('-'*16)
Test:
L = [4, 10, 8, 12, 6, 14, 2, 16, 1]
bubbleSort(L)
print(L)
Output:
i= 8 | [4, 10, 8, 12, 6, 14, 2, 16, 1]
i= 8 | 10 <-> 8 => [4, 8, 10, 12, 6, 14, 2, 16, 1]
i= 8 | 12 <-> 6 => [4, 8, 10, 6, 12, 14, 2, 16, 1]
i= 8 | 14 <-> 2 => [4, 8, 10, 6, 12, 2, 14, 16, 1]
i= 8 | 16 <-> 1 => [4, 8, 10, 6, 12, 2, 14, 1, 16]
----------------
i= 7 | [4, 8, 10, 6, 12, 2, 14, 1, 16]
i= 7 | 10 <-> 6 => [4, 8, 6, 10, 12, 2, 14, 1, 16]
i= 7 | 12 <-> 2 => [4, 8, 6, 10, 2, 12, 14, 1, 16]
i= 7 | 14 <-> 1 => [4, 8, 6, 10, 2, 12, 1, 14, 16]
----------------
i= 6 | [4, 8, 6, 10, 2, 12, 1, 14, 16]
i= 6 | 8 <-> 6 => [4, 6, 8, 10, 2, 12, 1, 14, 16]
i= 6 | 10 <-> 2 => [4, 6, 8, 2, 10, 12, 1, 14, 16]
i= 6 | 12 <-> 1 => [4, 6, 8, 2, 10, 1, 12, 14, 16]
----------------
i= 5 | [4, 6, 8, 2, 10, 1, 12, 14, 16]
i= 5 | 8 <-> 2 => [4, 6, 2, 8, 10, 1, 12, 14, 16]
i= 5 | 10 <-> 1 => [4, 6, 2, 8, 1, 10, 12, 14, 16]
----------------
i= 4 | [4, 6, 2, 8, 1, 10, 12, 14, 16]
i= 4 | 6 <-> 2 => [4, 2, 6, 8, 1, 10, 12, 14, 16]
i= 4 | 8 <-> 1 => [4, 2, 6, 1, 8, 10, 12, 14, 16]
----------------
i= 3 | [4, 2, 6, 1, 8, 10, 12, 14, 16]
i= 3 | 4 <-> 2 => [2, 4, 6, 1, 8, 10, 12, 14, 16]
i= 3 | 6 <-> 1 => [2, 4, 1, 6, 8, 10, 12, 14, 16]
----------------
i= 2 | [2, 4, 1, 6, 8, 10, 12, 14, 16]
i= 2 | 4 <-> 1 => [2, 1, 4, 6, 8, 10, 12, 14, 16]
----------------
i= 1 | [2, 1, 4, 6, 8, 10, 12, 14, 16]
i= 1 | 2 <-> 1 => [1, 2, 4, 6, 8, 10, 12, 14, 16]
----------------
[1, 2, 4, 6, 8, 10, 12, 14, 16]